import uvicorn
import sys
import threading
import ttkbootstrap as ttk

from ttkbootstrap.constants import *

from src.config import check_config
from src.server import app as fastapi_app
from src.ui import TranslationApp
from src.log import DEBUG, SCRIPTP


class MainApp:
    def __init__(self):
        self.root = ttk.Window(title="同声传译", themename="cosmo", iconphoto=str(SCRIPTP.joinpath("logo.png")), size=(400, 180), resizable=(False, False), alpha=0)
        self.root.withdraw()
        
        self.server_thread = None
        self.is_server_running = False
        self.meeting_id = ""
        
        self.translation_app = TranslationApp(self.root, self.meeting_id)

        self.root.place_window_center()
        
    def start_server(self):
        if not self.is_server_running:
            self.server_thread = threading.Thread(
                target=uvicorn.run,
                args=(fastapi_app,),
                kwargs={"host": "0.0.0.0", "port": 9507, "log_level": "info"},
                daemon=True
            )
            self.server_thread.start()
            self.is_server_running = True
            print("FastAPI服务器已启动")
    
    def on_closing(self):
        """处理窗口关闭事件"""
        print("程序正在关闭...")
        self.translation_app.toggle_stop_recording()
        # 销毁窗口
        self.root.destroy()
    
    def run(self):
        self.start_server()
        if check_config(self.root):
            self.root.deiconify()
            self.root.attributes("-topmost", True)
            self.root.protocol("WM_DELETE_WINDOW", self.on_closing)
            self.root.attributes("-alpha", 1.0)
            self.root.mainloop()

if __name__ == "__main__":
    if not DEBUG:
        # 重定向标准输出到日志文件
        sys.stdout = open(SCRIPTP.joinpath("meeting.log"), "w")
        # 重定向标准错误到日志文件
        sys.stderr = open(SCRIPTP.joinpath("meeting.log"), "w")

    app = MainApp()
    app.run()
